<?php

namespace cms\modules\v1\models\shop;
use cms\modules\v1\models\Common;
use common\models\Functions;
use common\models\shop\GoodsDetailBanner;
use common\services\upload\Qiniu;
use yii\base\Exception;

/**
 * This is the model class for table "project_info".
 *
 * @property int $id
 * @property string $name
 */
class GoodsBanner extends GoodsDetailBanner
{

    /**
     * 保存每个规格的图片
     * @param int $goodsDetailId
     * @param array $banners
     * @throws Exception
     */
    public function saveBannerByGoodsDetailId($goodsDetailId = 0, $banners = []) {
        //删除旧图片（文件）

        $where['goods_detail_id'] = $goodsDetailId;
        $oldBanners = static::getByWhere($where, ['id', 'goods_image']);
        $oldImages = array_column($oldBanners, 'goods_image');
        $newImages = array_column($banners, 'name');
        foreach ($oldImages as $v) {
            if (!in_array($v, $newImages)) {
//                $oldFileFullPath = \Yii::getAlias("@uploads") . $v;
                $oldFileFullPath = $v;
                if (file_exists($oldFileFullPath)) {
                    //七牛删除旧图片
                    (new Qiniu()) -> deleteOldKey($oldFileFullPath);
//                    @unlink($oldFileFullPath);
                }
            }
        }
        //删除旧图片（数据库）
        static::deleteAll($where);
        //增加新图片
        $data['goods_detail_id'] = $goodsDetailId;
        $data['create_time'] = date('Y-m-d H:i:s');
        foreach ($newImages as $v) {
            $data['goods_image'] = $v;
            $res = static::insertDataWithLog($data);
            if ($res === false) {
                throw new Exception('系统错误,请联系开发小哥');
            }
        }
    }
}
